#!/bin/bash

# Define cover files array
covers=("$@")

filename="jjwxc-gl-cover-collage.jpg"

width=1440
height=768

# Book dimensions
max_width=232
max_height=324
page_border=3

# Step 1: Create background
magick -size ${width}x${height} \
    -define gradient:radii=1000,500 \
    radial-gradient:'#fefefe'-'#e9eae2' \
    -sigmoidal-contrast 6,50% \
    bg.jpg

# Step 2: Process each cover with shadow
processed_covers=()
for cover in "${covers[@]}"; do
    # Extract filename without extension
    name=$(basename "$cover" | cut -d. -f1)

    magick "$cover" \
        -resize ${max_width}x${max_height}^ \
        -gravity center \
        temp.png

    # Get actual resized dimensions
    actual_size=$(identify -format "%wx%h" temp.png)
    actual_width=${actual_size%%x*}
    actual_height=${actual_size##*x}

    # Add borders (pages and spine)
    magick -size "${actual_width}"x$((actual_height + 2 * page_border)) canvas:none \
        \( temp.png -geometry +0+${page_border} \) -composite \
        \( -size $((actual_width - 2 * page_border))x${page_border} gradient:'#f0f0f0'-'#d0d0d0' -geometry +${page_border}+$((actual_height + page_border)) \) \
        -compose over -composite \
        temp.png

    magick temp.png \
        \( +clone -background black -shadow 80x8+8+8 \) +swap \
        -background none -layers merge +repage \
        "shadow_$name.png"

    processed_covers+=("shadow_$name.png")
done

# Step 3: Create collage with spacing
montage "${processed_covers[@]}" \
    -background none -tile 5x2 -geometry +10+10 \
    covers.png

magick bg.jpg \
    \( covers.png \) -gravity center -compose over -composite \
    "$filename"

# Step 4: Add lighting effects

## Create light stripes
magick -size ${width}x${height} canvas:'#fffef022' \
    -fill black \
    -draw "rectangle 0,40 $width,60" \
    -draw "rectangle $((width / 3)),$((height * 4 / 5 + 10)) $width,$((height * 4 / 5 + 30))" \
    -draw "rectangle $((width / 6)),$((height - 70)) $width,$((height - 60))" \
    -blur 0x60 \
    -distort SRT -30 \
    light_stripes.png

# Combine all lighting effects
magick "$filename" \
    light_stripes.png -compose multiply -composite \
    "$filename"

# Cleanup
rm bg.jpg temp.png "${processed_covers[@]}" covers.png light_stripes.png

echo "Collage created: $filename"
